package com.ruoyi.ai.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.ruoyi.ai.api.bo.WxPhoneLoginBo;
import com.ruoyi.ai.api.vo.WxLoginVo;
import com.ruoyi.ai.service.WxBizService;
import com.ruoyi.common.core.domain.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 微信开放接口
 */
@Validated
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/open/wx")
public class OpenWxController {
    private final WxBizService wxBizService;
    private final WxMaService wxMaService;
    private final WxMaMessageRouter wxMaMessageRouter;

    /**
     * 微信小程序登录
     *
     * @param code
     * @return
     */
    @PostMapping("/ma/login")
    public R<WxLoginVo> login(String code) {
        return R.ok(wxBizService.login(code));
    }

    /**
     * 微信小程序授权手机号登录
     * 暂不支持
     *
     * @param wxPhoneLoginBo
     * @return
     */
    @PostMapping("/ma/loginByPhone")
    public R<WxLoginVo> login(@RequestBody WxPhoneLoginBo wxPhoneLoginBo) {
        return R.ok(wxBizService.loginByPhone(wxPhoneLoginBo));
    }

    /**
     * 微信小程序模拟登录，方便后端调试接口
     *
     * @param wxPhoneLoginBo
     * @return
     */
    @PostMapping("/ma/mockLogin")
    public R<WxLoginVo> mockLogin(@RequestBody WxPhoneLoginBo wxPhoneLoginBo) {
        return R.ok(wxBizService.mockLogin(wxPhoneLoginBo));
    }

    //------ 以下如果没有需要可不对接 ---------

    @GetMapping(value = ("/ma/portal"), produces = "text/plain;charset=utf-8")
    public String authGet(
        @RequestParam(name = "signature", required = false) String signature,
        @RequestParam(name = "timestamp", required = false) String timestamp,
        @RequestParam(name = "nonce", required = false) String nonce,
        @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
            signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        if (wxMaService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @PostMapping(value = "/ma/portal")
    public String post(@RequestBody String requestBody,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "encrypt_type", required = false) String encryptType,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n接收微信请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            msgSignature, encryptType, signature, timestamp, nonce, requestBody);
        final boolean isJson = Objects.equals(wxMaService.getWxMaConfig().getMsgDataFormat(),
            WxMaConstants.MsgDataFormat.JSON);
        if (StringUtils.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {//xml
                inMessage = WxMaMessage.fromXml(requestBody);
            }

            this.route(inMessage);
            return "success";
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxMaService.getWxMaConfig());
            } else {//xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxMaService.getWxMaConfig(),
                    timestamp, nonce, msgSignature);
            }

            this.route(inMessage);
            return "success";
        }
        throw new RuntimeException("不可识别的加密类型：" + encryptType);
    }

    private void route(WxMaMessage message) {
        try {
            wxMaMessageRouter.route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
